/**
 * Mar 28, 2010
 */
package org.tomale.id;

import java.sql.Connection;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.preference.IPreferenceStore;
import org.tomale.id.common.KeyValuePair;
import org.tomale.id.ui.Activator;
import org.tomale.id.ui.preference.pages.PreferenceConstants;

/**
 * @author ferd
 *
 */
public class ConnectionManager {

	private static Connection _cn;
	
	public final static String EXT_ID_CONNECTION = "org.tomale.id.connection.provider";
	
	/**
	 * get a database connection from pool
	 * if multiple database connections are available,
	 * show a dialog box for selection
	 * @return
	 */
	public static Connection getConnection() throws ProviderException {
		if(_cn == null){
			IPreferenceStore store = Activator.getDefault().getPreferenceStore();
			String provider = store.getString(PreferenceConstants.CONNECTION_PID);
			String url = store.getString(PreferenceConstants.CONNECTION_URL);
			String user = store.getString(PreferenceConstants.CONNECTION_USR);
			String pw = store.getString(PreferenceConstants.CONNECTION_PW);
			if(provider.isEmpty() || url.isEmpty() || user.isEmpty() || pw.isEmpty()){
				throw new ProviderException("Connection provider preferences not properly set.");
			}
			
			IConfigurationElement[] elems = Platform.getExtensionRegistry().getConfigurationElementsFor(EXT_ID_CONNECTION);
			for(IConfigurationElement elem : elems){
				if(elem.getAttribute("class") == provider){
					try {
						Object o = elem.createExecutableExtension("class");
						if(o instanceof IConnectionProvider){
							IConnectionProvider cp = (IConnectionProvider) o;
							_cn = cp.getConnection(url, user, pw);
							break;
						}
					}catch(CoreException e){
						throw new ProviderException(MessageFormat.format("Unable to initialize provider '{0}'.", 
								provider),e);
					}
				}
			}
		}
		return _cn;
	}
	
	public static List<KeyValuePair<String, String>> getConnectionProviders(){
		ArrayList<KeyValuePair<String, String>> result = new ArrayList<KeyValuePair<String,String>>();
		
		IConfigurationElement[] elems = Platform.getExtensionRegistry().getConfigurationElementsFor(EXT_ID_CONNECTION);
		for(IConfigurationElement elem : elems){
			result.add(new KeyValuePair<String, String>(elem.getAttribute("class"), 
					elem.getAttribute("description")));
		}
		return result;
	}
}
